<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
use App\Models\ProcutSku;
use App\Models\Products;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ProductController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {

        $keyword=$request->input('keyword');
//        $where=[];
//        if(!empty($keyword)){
//            $where[]=['username'=>'like',"%$keyword%"];
//        }
        $data= Products::when($keyword,function($query) use($keyword){
            $query->where('name','like',"%$keyword%")->get();
        })->with(['cate','specs.spec','sku.name'])->paginate($request->input('limit',10));

        $totalMoney=Products::sum('sale');

        return $this->success(compact('data','totalMoney'));

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->offsetSet('banners',implode(',',$request->input('banners')));
        if(Products::create($request->all())) return $this->success();
        $this->error();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
       $product= Products::with(['specs.spec','sku.name','attr'])->find($id)->toArray();

//       foreach ($product['sku'] as $k=>&$v){
//        $ids=(explode(',',$v['specs_value_id']));
//        $a= DB::table('specs_value')->whereIn('id',$ids)->get();
//        $v['sku']['xx']=$a;
//
//    }

       return $this->success($product);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {



        $arr=$request->input('type');

        if(!empty($arr)){
            $data=[];

                foreach ($arr as $v){
                    $res['array_values']=  json_encode($v['array_values']);
                    $res['specs_value_id']=implode(',',array_column($v['array_values'],'id'));
                    $res['products_id']=$v['products_id'];
                    $res['price']=$v['price'];
                    $res['const_price']=$v['const_price'];
                    $res['stock']=$v['stock'];
                    $data[]=$res;
                    $id=$v['products_id'];
                }
                DB::table('products')->where('id',$id)->update(['is_spec'=>1]);
                DB::table('procut_sku')->where('products_id',$id)->delete();
                DB::table('procut_sku')->insert($data);
                return $this->success();
            }




//        return $this->success();
//         $data= $request->merge(['array_values'=>json_encode($request->input('array_values'))]);


        if($request->input('banners')){
            $request->offsetSet('banners',implode(',',$request->input('banners')));
        }

        if(Products::where('id',$id)->update($request->all())) return $this->success();
        $this->error();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if(Products::destroy($id)) return $this->success();
        $this->error();
    }

    /**
     * 商品数据分析
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function analyse(Request $request)
    {
        $keyword=$request->input('keyword');
        $time=$request->input('time');
        $res=[1=>'sale_num|desc',2=>'sale_num|asc',3=>'browse|desc',4=>'browse|asc'];
       $data= DB::table('products')
           ->when($keyword,function ($query) use($keyword,$res) {
               foreach ($res as $k=>$v){
                   if($k==$keyword){
                       $query->orderBy(explode('|',$v)[0],explode('|',$v)[1]);
                   }
               }
           } )
           ->when($time,function ($query) use($time){
                $start=strtotime(explode(',',$time)[0]);
                $end=strtotime(explode(',',$time)[1]);
               $query->whereBetween('created_at',[$start,$end]);
           })
           ->offset($request->input('page',1))->limit($request->input('limit',10))->get();
       $total=DB::table('products')->count();
        foreach ($data as &$item){
            $item->total=sprintf("%.2f",$item->sale_num*$item->sale); //保留两位小数，不四舍五入
        }
        return $this->success(compact('data','total'));
    }
}
